package com.zzyl.nursing.service.impl;

import java.util.*;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.RedisKeyConstants;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.FamilyListVo;
import com.zzyl.nursing.vo.HealthMsgVo;
import com.zzyl.nursing.vo.LoginVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import javax.servlet.http.HttpServletRequest;
/**
 * 老人家属Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-26
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Autowired
    private ElderMapper elderMapper;

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember)?1:0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember)?1:0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    /**
     * 小程序端登录
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //获取openid  微信接口获取
        String openid = wechatService.getOpenid(dto.getCode());

        //根据openid查询用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid));

        //如果用户为空，构建用户，赋值一个openid
        if(ObjectUtil.isEmpty(familyMember)){
            familyMember = FamilyMember
                    .builder()
                    .openId(openid)
                    .build();
        }

        //获取用户的手机号  微信接口获取
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //保存或更新用户
        insertOrUpdateFamilyMember(familyMember,phone);

        //生成token返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("userName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);

        return loginVo;
    }



    /**
     * 保存或更新用户
     * @param familyMember
     * @param phone
     */
    private void insertOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //判断手机号与数据库的手机号是否一致
        if(ObjectUtil.notEqual(familyMember.getPhone(),phone)){
            familyMember.setPhone(phone);
        }
        //判断是否存在id，如果存在id，则更新，不存在则保存
        if(ObjectUtil.isNotEmpty(familyMember.getId())){
            updateById(familyMember);
            return;
        }
        //获取用户的昵称
        int index = (int)(Math.random() * DEFAULT_NICKNAME_PREFIX.size());
        String nickName = DEFAULT_NICKNAME_PREFIX.get(index) + StringUtils.substring(phone,7,11);
        familyMember.setName(nickName);
        //保存
        save(familyMember);
    }




//    @Autowired
//    private BedMapper bedMapper;
//
//    @Autowired
//    private RoomMapper roomMapper;
//
//    @Autowired
//    private DeviceMapper deviceMapper;
//    @Autowired
//    private HttpServletRequest request;


//    @Override
//    public List<FamilyListVo> listByPage() {
//        request.getHeader("authorization");
//        String token = request.getHeader("authorization");
//        Claims claims = tokenService.parseToken(token);
//        Object id = claims.get("userId");
//        Long userId = Long.valueOf(id.toString());
//        //解析token获取当前登录用户的id
////        Long userId = UserThreadLocal.getUserId();
//
//        //根据userId查询客户老人中间表获取客户老人中间表id、客户对老人的称谓
//        List<FamilyMemberElder> familyMemberElderList = familyMemberElderMapper.selectList(Wrappers.<FamilyMemberElder>lambdaQuery()
//                .eq(FamilyMemberElder::getFamilyMemberId, userId)
//        );
//
//        List<FamilyListVo> resultList = new ArrayList<>();
//        //遍历中间表数据
//        for (FamilyMemberElder item : familyMemberElderList) {
//            FamilyListVo familyListVo = new FamilyListVo();
//            //设置中间表信息
//            familyListVo.setMid(item.getId());
//            familyListVo.setMremark(item.getRemark());
//            familyListVo.setElderId(item.getElderId());
//            //查询老人信息
//            Elder elder = elderMapper.selectElderById(item.getElderId());
//            if (elder != null) {
//                //设置老人基本信息
//                familyListVo.setName(elder.getName());
//                familyListVo.setImage(elder.getImage());
//                familyListVo.setBedNumber(elder.getBedNumber());
//                //查询床位和房间信息
//                if (elder.getBedId() != null) {
//                    Bed bed = bedMapper.selectBedById(elder.getBedId());
//                    if (bed != null && bed.getRoomId() != null) {
//                        Room room = roomMapper.selectRoomById(bed.getRoomId());
//                        if (room != null) {
//                            familyListVo.setTypeName(room.getTypeName());
//                        }
//                    }
//                }
//                //根据老人姓名查询设备信息
//                LambdaQueryWrapper<Device> deviceWrapper = new LambdaQueryWrapper<Device>()
//                        .eq(Device::getBindingLocation,elder.getId())
//                        .select(Device::getBindingLocation);
//                Device device = deviceMapper.selectOne(deviceWrapper);
//                if (device != null) {
//                    familyListVo.setIotId(device.getIotId());
//                    familyListVo.setDeviceName(device.getDeviceName());
//                    familyListVo.setProductKey(device.getProductKey());
//                }
//            }
//            resultList.add(familyListVo);
//        }
//        return resultList;
//    }


//    @Autowired
//    private RedisTemplate<String, String> redisTemplate;
//    @Override
//    public List<HealthMsgVo> queryServiceProperties(String iotId) {
//        // 初始化返回列表
//        ArrayList<HealthMsgVo> voList = new ArrayList<>();
//
//        try {
//            // 从Redis获取设备数据
//            Object data = redisTemplate.opsForHash().get(RedisKeyConstants.IOT_DEVICE_LAST_DATA, iotId);
//
//            if (data != null) {
//                // 类型转换
//                List<DeviceData> list = (List<DeviceData>) data;
//
//                // 遍历处理每个设备数据
//                for (DeviceData deviceData : list) {
//                    HealthMsgVo vo = new HealthMsgVo();
//
//                    // 设置设备属性
//                    vo.setFunctionId(deviceData.getFunctionId());
//                    vo.setEventTime(deviceData.getAlarmTime());
//                    vo.setValue(deviceData.getDataValue());
//                    voList.add(vo);
//                }
//            }
//        } catch (Exception e) {
//            log.error("查询设备属性异常，iotId: {}");
//        }
//        return voList;
//    }
}
